package cn.mdmm.controller;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.modoumama.common.utils.StringUtils;
import cn.modoumama.page.Page;


public class BaseController{

	protected Logger logger = LoggerFactory.getLogger(getClass());
	/**
	 *
	 * @param request
	 * @return
	 * @throws BusinessException
	 */
	protected Page getPage(HttpServletRequest request){
		return getPage(request,null);
	}
	
	/**
	*order asc
	 *page	1
	 *rows	10
	 *sort	roleId
	 * @param request
	 * @param orderByClause
	 * @return
	 */
	protected Page getPage(HttpServletRequest request,
			String orderByClause){
		Page page = new Page();
		String currPageStr = request.getParameter("page");
		String pageSizeStr = request.getParameter("rows");
		String property = request.getParameter("sort");
		if (StringUtils.isEmpty(orderByClause)) {
			if (!StringUtils.isEmpty(property)) {
				orderByClause = getColumn(property) + " "
						+ request.getParameter("order");
			}
		}
		try{
			page.setCurrPage(Integer.valueOf(currPageStr));
			page.setPageSize(Integer.valueOf(pageSizeStr));
		}catch(NumberFormatException e){
			page.setCurrPage(1);
			page.setPageSize(Integer.MAX_VALUE);
		}
		page.addCondition("orderByClause", orderByClause);
		return page;
	}

	private String getColumn(String property) {
		StringBuffer buffer = new StringBuffer(property);
		for (int i = 0; i < buffer.length(); i++) {
			char c = buffer.charAt(i);
			if(Character.isUpperCase(c)){
				buffer.insert(i++, '_');
			}
		}
		return buffer.toString();
	}
}